import * as vscode from 'vscode';

/**
 * update configuration the human way
 * @async
 * @param uri
 * @param val
 * @param [target] - desired location, if you like the bother
 */
export async function updateConfiguration(uri: string, val: any,
      target?: vscode.ConfigurationTarget) {
  let m = uri.match(/^(?<namespace>\S+)\.(?<name>\S+)$/);
  if (m === null)
    throw new Error('uri value error');
  let { namespace, name } = m.groups!;
  let config = vscode.workspace.getConfiguration(namespace);
  let curval = config.inspect(name);
  if (typeof curval === 'undefined')
    throw new Error('invalid uri');
  /* target, if specified, is top priority */
  if (typeof target !== 'undefined') {
    await config.update(name, val, target);
    return;
  }
  /* else, update to the current effective location (@see {config.get()}) */
  if (typeof curval.workspaceFolderValue !== 'undefined') {
    await config.update(name, val, vscode.ConfigurationTarget.WorkspaceFolder);
    return;
  }
  if (typeof curval.workspaceValue !== 'undefined') {
    await config.update(name, val, vscode.ConfigurationTarget.Workspace);
    return;
  }
  await config.update(name, val, vscode.ConfigurationTarget.Global);
}
